#ifndef T_CMD_BUS_H
#define T_CMD_BUS_H

#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

#if defined(ENABLE_DEBUG_LOG) && (ENABLE_DEBUG_LOG == 1)
#define BUS_LOG_DEBUG(fmt, ...) printf("[DEBUG] " fmt "\n", ##__VA_ARGS__)
#else
#define BUS_LOG_DEBUG(fmt, ...) do {} while(0)
#endif

// section 宏适配
#ifndef BUS_SECTION
#   if defined(__CC_ARM) || defined(__CLANG_ARM) || defined(__GNUC__)
#       define BUS_SECTION(x) __attribute__((section(x), used))
#   elif defined(__IAR_SYSTEMS_ICC__)
#       define BUS_SECTION(x) @ x
#   else
#       define BUS_SECTION(x)
#   endif
#endif

#ifndef BUS_USED
#   if defined(__GNUC__) || defined(__CC_ARM) || defined(__CLANG_ARM)
#       define BUS_USED __attribute__((used))
#   elif defined(__IAR_SYSTEMS_ICC__)
#       define BUS_USED __root
#   else
#       define BUS_USED
#   endif
#endif

// 回调结构
typedef bool (*cmd_bus_callback)(void *param, const char *cmd, char *response, size_t buffer_size);

typedef struct Object_Command_Bus {
    void *param;
    char *cmd_name;
    cmd_bus_callback bus_callback;
    struct Object_Command_Bus *next;
} Object_Command_Bus;

// 链表头
extern Object_Command_Bus *command_bus_list;

// 注册函数，所有平台都需调用
void cmd_bus_register(Object_Command_Bus *cmd);
void cmd_bus_cb(const char *cmd, char *response, size_t buffer_size);
size_t get_command_bus_list_length(void);

// 宏：跨平台命令注册（自动 + 手动）
#define BUS_CMD_ADD(user, name, callback)                                \
    static Object_Command_Bus BUS_CMD_##name = {                         \
        .param = user,                                                   \
        .cmd_name = #name,                                               \
        .bus_callback = callback,                                        \
        .next = NULL                                                     \
    };                                                                   \
    static void BUS_CMD_REG_##name(void) {                               \
        cmd_bus_register(&BUS_CMD_##name);                               \
    }                                                                    \
    BUS_USED static void (*BUS_CMD_##name##_ptr)(void) = BUS_CMD_REG_##name;

// 统一注册调用（main中调用）
void register_all_commands(void);

#ifdef __cplusplus
}
#endif

#endif /* T_CMD_BUS_H */
